/**
 * 卷帘对比(mars3d实现)
 *
 * @param   viewer          cesium实例
 * @param   showLine        是否显示分割线
 */
import { globalTool } from './BQGIS-globalVar'

export function initBQGIS_split({
    viewer = window.viewer
}) {
    if (!globalTool.split) {
        globalTool.split = new mars3d.control.MapSplit({})
        globalTool.split.changedLayerId = [] // 备份数据，存储切分实体的id，用于在恢复默认时批量处理
        viewer.addControl(globalTool.split)
    }
    return globalTool.split
}

/**
 * 切换(左/右屏)
 *
 * @param   obj             Cesium3DTileset/ImageryLayer 实体
 * @param   splitDirection  left/right/none
 */
export function setSplitDirection(obj, splitDirection) {
    const direction = splitDirection.toUpperCase()
    if (obj.layer instanceof Cesium.Cesium3DTileset || obj.layer instanceof Cesium.ImageryLayer) {
        obj.layer.splitDirection = Cesium.SplitDirection[direction]
        const index = globalTool.split.changedLayerId.indexOf(obj.id)
        if(direction === 'RIGHT' || direction === 'LEFT'){
            if(index === -1){
                globalTool.split.changedLayerId.push(obj.id)
            }
        }
        if(direction === 'NONE'){
            if(index !== -1){
                globalTool.split.changedLayerId.splice(index, 1)
            }
        }
    }
}

/**
 * 获取方向
 *
 * @param   obj             Cesium3DTileset/ImageryLayer 实体
 * 
 * @reture  left/right/none
 */
export function getSplitDirection(obj) {
    if (obj instanceof Cesium.Cesium3DTileset || obj instanceof Cesium.ImageryLayer) {
        const directionMap = {
            [Cesium.SplitDirection.LEFT]: 'left',
            [Cesium.SplitDirection.RIGHT]: 'right',
            [Cesium.SplitDirection.NONE]: 'none'
        }
        return directionMap[obj.splitDirection]
    }
}


/**
 * 批量切换(左/右屏)
 *
 * @param   arr             实体数组
 * @param   splitDirection  left/right/none
 */
export function mSetSplitDirection(arr, splitDirection) {
    const direction = splitDirection.toUpperCase()
    arr.forEach(item => {
        setSplitDirection(item, direction)
    })
}

// 全部恢复默认
export function resetLayer (viewer = window.viewer) {
    globalTool.split.changedLayerId.forEach(id => {
        const layer = viewer.getLayerById(id)
        if(layer){
            layer.layer.splitDirection = Cesium.SplitDirection.NONE
        }
    })
}